package com.yjz.designpattern.strategy_pattern.factory;

import com.yjz.designpattern.strategy_pattern.strategy.CashierBizTypeEnum;
import com.yjz.designpattern.strategy_pattern.strategy.LaunchPayStrategy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author: yuanjinzhong
 * @date: 2022/10/12 7:34 PM
 * @description:
 */
@Component
public class LaunchPayFactory implements ApplicationContextAware {

  private List<LaunchPayStrategy> list = new ArrayList();

  public Optional<LaunchPayStrategy> obtainStrategy(CashierBizTypeEnum bizType) {
    return list.stream().filter(x -> x.support(bizType)).findFirst();
  }

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.list.addAll(
        BeanFactoryUtils.beansOfTypeIncludingAncestors(applicationContext, LaunchPayStrategy.class)
            .values());
  }
}
